<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="加载失败，请点击重试"
      @load="onLoad"
    >
      <van-cell v-for="(item, ind) in list" :key="ind" :title="item.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search';
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      typeof: String,
      require: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      per_page: 20,
      error: false
    };
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onLoad () {
      try {
        // 1.请求获取数据

        const { data } = await getSearchResult({
          page: this.page,
          per_page: this.per_page,
          q: this.searchText
        });
        // 模拟失败
        // if (Math.random() > 0.5) {
        //   JSON.parse("dsnajndjsa");
        // }
        // console.log(data);
        // 2.将数据添加到数组当中

        const { results } = data.data;

        this.list.push(...results);
        // 3.将本次加载中的loading关闭
        this.loading = false;
        // 4.判断是否还有数据
        if (results.length) {
          // 如果有,则更新下一页数据的页码
          this.page++;
        } else {
          // 如果没有,则将加载状态finished 设置为false
          this.finished = true;
        }
      } catch (error) {
        this.error = true;
        this.loading = false;
      }
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
    }
  }
};
</script>

<style scoped lang="less"></style>
